import React, { useState, useEffect } from 'react';
import {
  Modal,
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  message,
  Row,
  Col,
  Divider,
} from 'antd';
import dayjs from 'dayjs';
import { updateCheckinActivityApi } from '../../../api/checkin';
import { CHECKIN_STATUS_OPTIONS, CHECKIN_FREQUENCY_OPTIONS, CHECKIN_STATUS, DEFAULTS } from '../CheckType';

const { TextArea } = Input;
const { RangePicker } = DatePicker;
const { Option } = Select;

const EditActivity = ({ visible, activity, onCancel, onSuccess }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  // 获取当前用户ID
  const getCurrentUserId = () => 1; // 临时写死，实际应该从登录状态获取

  // 处理打卡频率变化，重新计算目标天数
  const handleFrequencyChange = (value) => {
    // 获取当前日期范围
    const dateRange = form.getFieldValue('dateRange');
    if (dateRange && dateRange.length === 2) {
      handleDateRangeChange(dateRange);
    }
  };

  // 处理日期范围变化，自动计算目标天数
  const handleDateRangeChange = (dates) => {
    if (dates && dates.length === 2) {
      const [startDate, endDate] = dates;
      const totalDays = endDate.diff(startDate, 'day') + 1; // 包含起始日期

      // 获取当前打卡频率，默认为每天
      const currentFrequency = form.getFieldValue('checkinFrequency') || 1;

      // 根据打卡频率计算实际目标天数
      const actualTargetDays = Math.ceil(totalDays / currentFrequency);

      form.setFieldsValue({ targetDays: actualTargetDays });
    }
  };

  // 当活动数据变化时，设置表单初始值
  useEffect(() => {
    if (visible && activity) {
      form.setFieldsValue({
        title: activity.title,
        description: activity.description,
        status: activity.status,
        checkinFrequency: activity.checkinFrequency || 1,
        targetDays: activity.targetDays,
        totalParticipants: activity.totalParticipants,
        dateRange: [
          dayjs(activity.startDate),
          dayjs(activity.endDate)
        ],
        tags: activity.tags || [],
      });
    }
  }, [visible, activity, form]);

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      // 处理日期范围
      const [startDate, endDate] = values.dateRange;
      
      const activityData = {
        id: activity.id,
        title: values.title,
        description: values.description,
        checkinFrequency: values.checkinFrequency,
        startDate: startDate.format('YYYY-MM-DD'),
        endDate: endDate.format('YYYY-MM-DD'),
        targetDays: values.targetDays,
        status: values.status,
        totalParticipants: values.totalParticipants || 0,
        updatedBy: getCurrentUserId(),
      };

      setLoading(true);
      const response = await updateCheckinActivityApi(activityData);
      
      if (response && response.code === '0') {
        message.success('活动更新成功！');
        onSuccess(); // 刷新父组件数据，父组件的onSuccess会负责关闭弹窗
      } else {
        message.error(response.msg || '更新失败');
      }
    } catch (error) {
      console.error('更新活动失败:', error);
      message.error('更新失败，请检查表单信息');
    } finally {
      setLoading(false);
    }
  };

  // 处理取消
  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  return (
    <Modal
      title="编辑打卡活动"
      visible={visible}
      onCancel={handleCancel}
      footer={[
        <Button key="cancel" onClick={handleCancel}>
          取消
        </Button>,
        <Button 
          key="submit" 
          type="primary" 
          loading={loading}
          onClick={handleSubmit}
        >
          保存
        </Button>,
      ]}
      width={600}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
      >
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              label="活动名称"
              name="title"
              rules={[
                { required: true, message: '请输入活动名称' },
                { max: 255, message: '活动名称不能超过255个字符' }
              ]}
            >
              <Input placeholder="请输入活动名称" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              label="活动描述"
              name="description"
              rules={[
                { required: true, message: '请输入活动描述' },
                { max: 1000, message: '活动描述不能超过1000个字符' }
              ]}
            >
              <TextArea 
                rows={4} 
                placeholder="请详细描述活动内容、目标和要求等"
              />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label="活动状态"
              name="status"
              rules={[{ required: true, message: '请选择活动状态' }]}
            >
              <Select placeholder="请选择活动状态">
                {CHECKIN_STATUS_OPTIONS.map(status => (
                  <Option key={status.value} value={status.value}>
                    {status.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="打卡频率"
              name="checkinFrequency"
              rules={[{ required: true, message: '请设置打卡频率' }]}
            >
              <Select placeholder="请选择打卡频率" onChange={handleFrequencyChange}>
                {CHECKIN_FREQUENCY_OPTIONS.map(option => (
                  <Option key={option.value} value={option.value}>
                    {option.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              label="活动时间"
              name="dateRange"
              rules={[{ required: true, message: '请选择活动时间范围' }]}
            >
              <RangePicker
                style={{ width: '100%' }}
                placeholder={['开始日期', '结束日期']}
                format="YYYY-MM-DD"
                disabledDate={(current) => current && current < dayjs().startOf('day')}
                onChange={handleDateRangeChange}
              />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label="目标天数"
              name="targetDays"
              rules={[
                { required: true, message: '请输入目标天数' },
                { type: 'number', min: 1, max: 365, message: '目标天数应在1-365天之间' }
              ]}
            >
              <Input
                type="number"
                placeholder="根据日期范围和打卡频率自动计算，也可手动修改"
                min={1}
                max={365}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="预计参与人数"
              name="totalParticipants"
              rules={[
                { type: 'number', min: 0, max: DEFAULTS.MAX_PARTICIPANTS, message: `参与人数不能超过${DEFAULTS.MAX_PARTICIPANTS}人` }
              ]}
            >
              <Input 
                type="number" 
                placeholder="0" 
                min={0}
                max={DEFAULTS.MAX_PARTICIPANTS}
              />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              label="活动标签"
              name="tags"
            >
              <Select
                mode="tags"
                placeholder="请输入活动标签，按回车确认"
                maxTagCount={5}
              />
            </Form.Item>
          </Col>
        </Row>

        <Divider />

        <div style={{ textAlign: 'center', color: '#666', fontSize: 12 }}>
          <p>⚠️ 注意：修改活动信息可能会影响参与者的打卡进度</p>
        </div>
      </Form>
    </Modal>
  );
};

export default EditActivity; 